All files / web/src/app/api/arcade/rooms/[roomId]/join route.ts

0% Statements 0/284
0% Branches 0/1
0% Functions 0/1
0% Lines 0/284

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
import bcrypt from 'bcryptjs'
import { NextResponse } from 'next/server'
import { getActivePlayers, getRoomActivePlayers } from '@/lib/arcade/player-manager'
import { getInvitation, acceptInvitation } from '@/lib/arcade/room-invitations'
import { getJoinRequest } from '@/lib/arcade/room-join-requests'
import { getRoomById, touchRoom } from '@/lib/arcade/room-manager'
import { addRoomMember, getRoomMembers } from '@/lib/arcade/room-membership'
import { isUserBanned } from '@/lib/arcade/room-moderation'
import { withAuth } from '@/lib/auth/withAuth'
import { getSocketIO } from '@/lib/socket-io'
import { getUserId } from '@/lib/viewer'

/**
 * POST /api/arcade/rooms/:roomId/join
 * Join a room
 * Body:
 *   - displayName?: string (optional, will generate from userId if not provided)
 *   - password?: string (required for password-protected rooms)
 */
export const POST = withAuth(async (request, { params }) => {
  try {
    const { roomId } = (await params) as { roomId: string }
    const userId = await getUserId()
    const body = await request.json().catch(() => ({}))

    console.log(`[Join API] User ${userId} attempting to join room ${roomId}`)

    // Get room
    const room = await getRoomById(roomId)
    if (!room) {
      console.log(`[Join API] Room ${roomId} not found`)
      return NextResponse.json({ error: 'Room not found' }, { status: 404 })
    }

    console.log(
      `[Join API] Room ${roomId} found: name="${room.name}" accessMode="${room.accessMode}" game="${room.gameName}"`
    )

    // Check if user is banned
    const banned = await isUserBanned(roomId, userId)
    if (banned) {
      return NextResponse.json({ error: 'You are banned from this room' }, { status: 403 })
    }

    // Check if user is already a member (for locked/retired room access)
    const members = await getRoomMembers(roomId)
    const isExistingMember = members.some((m) => m.userId === userId)
    const isRoomCreator = room.createdBy === userId

    // Track invitation/join request to mark as accepted after successful join
    let invitationToAccept: string | null = null
    let joinRequestToAccept: string | null = null

    // Check for pending invitation (regardless of access mode)
    // This ensures invitations are marked as accepted when user joins ANY room type
    const invitation = await getInvitation(roomId, userId)
    if (invitation && invitation.status === 'pending') {
      invitationToAccept = invitation.id
      console.log(
        `[Join API] Found pending invitation ${invitation.id} for user ${userId} in room ${roomId}`
      )
    }

    // Validate access mode
    switch (room.accessMode) {
      case 'locked':
        // Allow existing members to continue using the room, but block new members
        if (!isExistingMember) {
          return NextResponse.json(
            { error: 'This room is locked and not accepting new members' },
            { status: 403 }
          )
        }
        break

      case 'retired':
        // Only the room creator can access retired rooms
        if (!isRoomCreator) {
          return NextResponse.json(
            {
              error: 'This room has been retired and is only accessible to the owner',
            },
            { status: 410 }
          )
        }
        break

      case 'password': {
        if (!body.password) {
          return NextResponse.json(
            { error: 'Password required to join this room' },
            { status: 401 }
          )
        }
        if (!room.password) {
          return NextResponse.json({ error: 'Room password not configured' }, { status: 500 })
        }
        const passwordMatch = await bcrypt.compare(body.password, room.password)
        if (!passwordMatch) {
          return NextResponse.json({ error: 'Incorrect password' }, { status: 401 })
        }
        break
      }

      case 'restricted': {
        console.log(`[Join API] Room is restricted, checking invitation for user ${userId}`)
        // Room creator can always rejoin their own room
        if (!isRoomCreator) {
          // For restricted rooms, invitation is REQUIRED
          if (!invitationToAccept) {
            console.log(`[Join API] No valid pending invitation, rejecting join`)
            return NextResponse.json(
              { error: 'You need a valid invitation to join this room' },
              { status: 403 }
            )
          }
          console.log(`[Join API] Valid invitation found, will accept after member added`)
        } else {
          console.log(`[Join API] User is room creator, skipping invitation check`)
        }
        break
      }

      case 'approval-only': {
        // Room creator can always rejoin their own room without approval
        if (!isRoomCreator) {
          // Check for approved join request
          const joinRequest = await getJoinRequest(roomId, userId)
          if (!joinRequest || joinRequest.status !== 'approved') {
            return NextResponse.json(
              { error: 'Your join request must be approved by the host' },
              { status: 403 }
            )
          }
          // Note: Join request stays in "approved" status after join
          // (No need to update it - "approved" indicates they were allowed in)
          joinRequestToAccept = joinRequest.id
        }
        break
      }
      default:
        // No additional checks needed
        break
    }

    // Get or generate display name
    const displayName = body.displayName || `Guest ${userId.slice(-4)}`

    // Validate display name length
    if (displayName.length > 50) {
      return NextResponse.json(
        { error: 'Display name too long (max 50 characters)' },
        { status: 400 }
      )
    }

    // Add member (with auto-leave logic for modal room enforcement)
    const { member, autoLeaveResult } = await addRoomMember({
      roomId,
      userId: userId,
      displayName,
      isCreator: false,
    })

    // Mark invitation as accepted (if applicable)
    if (invitationToAccept) {
      await acceptInvitation(invitationToAccept)
      console.log(`[Join API] Accepted invitation ${invitationToAccept} for user ${userId}`)
    }
    // Note: Join requests stay in "approved" status (no need to update)

    // Broadcast member-left events to any rooms the user was auto-left from
    if (autoLeaveResult && autoLeaveResult.leftRooms.length > 0) {
      const io = await getSocketIO()
      if (io) {
        for (const leftRoomId of autoLeaveResult.leftRooms) {
          try {
            // Get current members/players of the room the user left
            const leftRoomMembers = await getRoomMembers(leftRoomId)
            const leftRoomPlayers = await getRoomActivePlayers(leftRoomId)

            // Convert to object for JSON serialization
            const leftRoomPlayersObj: Record<string, any[]> = {}
            for (const [uid, players] of leftRoomPlayers.entries()) {
              leftRoomPlayersObj[uid] = players
            }

            // Broadcast to all remaining users in the old room
            io.to(`room:${leftRoomId}`).emit('member-left', {
              roomId: leftRoomId,
              userId: userId,
              members: leftRoomMembers,
              memberPlayers: leftRoomPlayersObj,
              reason: 'auto-left', // Indicate this was automatic, not voluntary
            })

            console.log(
              `[Join API] Broadcasted member-left for user ${userId} in room ${leftRoomId} (auto-leave)`
            )
          } catch (socketError) {
            console.error(
              `[Join API] Failed to broadcast member-left for room ${leftRoomId}:`,
              socketError
            )
          }
        }
      }
    }

    // Fetch user's active players (these will participate in the game)
    const activePlayers = await getActivePlayers(userId)

    // Update room activity to refresh TTL
    await touchRoom(roomId)

    // Broadcast to all users in the room via socket
    const io = await getSocketIO()
    if (io) {
      try {
        const members = await getRoomMembers(roomId)
        const memberPlayers = await getRoomActivePlayers(roomId)

        // Convert memberPlayers Map to object for JSON serialization
        const memberPlayersObj: Record<string, any[]> = {}
        for (const [uid, players] of memberPlayers.entries()) {
          memberPlayersObj[uid] = players
        }

        // Broadcast to all users in this room
        io.to(`room:${roomId}`).emit('member-joined', {
          roomId,
          userId: userId,
          members,
          memberPlayers: memberPlayersObj,
        })

        console.log(`[Join API] Broadcasted member-joined for user ${userId} in room ${roomId}`)
      } catch (socketError) {
        // Log but don't fail the request if socket broadcast fails
        console.error('[Join API] Failed to broadcast member-joined:', socketError)
      }
    }

    // Build response with auto-leave info if applicable
    console.log(
      `[Join API] Successfully added user ${userId} to room ${roomId} (invitation=${invitationToAccept ? 'accepted' : 'N/A'})`
    )

    return NextResponse.json(
      {
        member,
        room,
        activePlayers, // The user's active players that will join the game
        autoLeave: autoLeaveResult
          ? {
              roomIds: autoLeaveResult.leftRooms,
              message: `You were automatically removed from ${autoLeaveResult.leftRooms.length} other room(s)`,
            }
          : undefined,
      },
      { status: 201 }
    )
  } catch (error: any) {
    console.error('Failed to join room:', error)

    // Handle specific constraint violation error
    if (error.message?.includes('ROOM_MEMBERSHIP_CONFLICT')) {
      return NextResponse.json(
        {
          error: 'You are already in another room',
          code: 'ROOM_MEMBERSHIP_CONFLICT',
          message:
            'You can only be in one room at a time. Please leave your current room before joining a new one.',
          userMessage:
            '⚠️ Already in Another Room\n\nYou can only be in one room at a time. Please refresh the page and try again.',
        },
        { status: 409 } // 409 Conflict
      )
    }

    // Generic error
    return NextResponse.json({ error: 'Failed to join room' }, { status: 500 })
  }
})